package com.it.sonny.edpcommon.handler;

import com.it.sonny.edpcommon.dto.ApiResponse;
import com.it.sonny.edpcommon.excpetion.BusinessException;
import com.it.sonny.edpcommon.excpetion.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ApiResponse<Void>> handleBusiness(BusinessException e) {
        log.warn("业务异常: {}", e.getMessage(), e);
        return ResponseEntity.badRequest()
                .body(ApiResponse.error(e.getErrorEnum().getCode(), e.getErrorEnum().getMessage()));
    }

    @ExceptionHandler(SystemException.class)
    public ResponseEntity<ApiResponse<Void>> handleSystem(SystemException e) {
        log.error("系统异常: {}", e.getMessage(), e);
        return ResponseEntity.internalServerError()
                .body(ApiResponse.error(e.getErrorEnum().getCode(), e.getErrorEnum().getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<Void>> handleOther(Exception e) {
        log.error("未知异常", e);
        return ResponseEntity.internalServerError()
                .body(ApiResponse.error("SYS-500-0009", "服务器内部错误"));
    }
}
